"""
import socket,os
m = os.path.dirname(__file__)
n= os.path.join(m,"xxx\\cat.jpg")

sk = socket.socket()
sk.bind(("127.1.1.1",888))
sk.listen(5)

while True:

    conn,address= sk.accept()
    has_bytes = int(str(conn.recv(1024),"utf-8"))   # -> a-a
    has_num = 0

    if os.path.exists(n) :
        conn.sendall(bytes("100", "utf-8"))   # b -b
        has_num = os.stat(n).st_size
        conn.sendall(bytes(str(has_num),encoding="utf-8")) #c-c
        with open(n,"ab") as f:
            while has_num < has_bytes:
                line_bytes = conn.recv(1024)  #d-d
                f.write(line_bytes)
                has_num += len(line_bytes)
    else:
        conn.sendall(bytes("101","utf-8"))
        f = open(n,"wb")
        while has_num < has_bytes:
            line_bytes = conn.recv(1024)   #e-e
            f.write(line_bytes)
            has_num += len(line_bytes)
        f.close()
"""
import socketserver,os

m = os.path.dirname(__file__)
n= os.path.join(m,"xxx","cat.jpg")

class MyServer(socketserver.BaseRequestHandler):
    def handle(self):
        conn = self.request
        while True:
            has_bytes = int(str(conn.recv(1024), "utf-8"))  # -> a-a
            has_num = 0
            if os.path.exists(n):
                conn.sendall(bytes("100", "utf-8"))  # b -b
                has_num = os.stat(n).st_size
                conn.sendall(bytes(str(has_num), encoding="utf-8"))  # c-c
                with open(n, "ab") as f:
                    while has_num < has_bytes:
                        line_bytes = conn.recv(1024)  # d-d
                        f.write(line_bytes)
                        has_num += len(line_bytes)
            else:
                conn.sendall(bytes("101", "utf-8"))
                f = open(n, "wb")
                while has_num < has_bytes:
                    line_bytes = conn.recv(1024)  # e-e
                    f.write(line_bytes)
                    has_num += len(line_bytes)
                f.close()

if __name__ == '__main__':
    server = socketserver.ThreadingTCPServer(("127.1.1.1",888),MyServer)
    server.serve_forever()

